﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using log4net;

namespace FileDistributor.Service
{
    [RunInstaller(true)]
    public class FileDistributorServiceInstaller : Installer
    {
        private readonly ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private const string _serviceName = "FileDistributorService";

        public FileDistributorServiceInstaller()
        {
            var processInstaller = new ServiceProcessInstaller();
            var serviceInstaller = new ServiceInstaller();

            //set the privileges
            processInstaller.Account = ServiceAccount.LocalSystem;

            serviceInstaller.DisplayName = "File Distributor";
            serviceInstaller.StartType = ServiceStartMode.Automatic;

            //must be the same as what was set in Program's constructor
            serviceInstaller.ServiceName = _serviceName;
            serviceInstaller.Description = "Tjänst för distribuering av filer";

            Installers.Add(processInstaller);
            Installers.Add(serviceInstaller);
        }

        protected override void OnAfterInstall(System.Collections.IDictionary savedState)
        {
            base.OnAfterInstall(savedState);

            StartServiceIfStopped();
        }

        private void StartServiceIfStopped()
        {
            try
            {
                ServiceController service = new ServiceController();
                service.ServiceName = _serviceName;

                string serviceStatus = service.Status.ToString();
                if (serviceStatus == "Stopped")
                {
                    service.Start();
                }
            }
            catch
            {
                _logger.Warn("Failed to start service automaticly after install.");
            }
        }
    }

}
